package com.novunda.platform.web;

import com.novunda.platform.common.utils.JsonUtils;
import com.novunda.platform.common.utils.MailUtil;
import com.novunda.platform.common.utils.StringUtil;
import com.novunda.platform.entities.EmailInfo;
import com.novunda.platform.services.EmailService;
import com.novunda.platform.web.model.ReturnModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 邮件发送
 * Created by YJY on 2016/9/22.
 */
@RestController
public class EmailSendController {

    /**
     * 邮件服务
     */
    @Autowired
    private EmailService emailService;

    /**
     * 发送邮件
     *
     * @param organization 机构
     * @param emailTheme   邮件主题
     * @param emailContent 邮件内容
     * @param receiver     接收者
     */
    @RequestMapping(value = "/esc/se")
    public String sendEmail(String organization, String emailTheme, String emailContent, String receiver) {
        //参数验证
        if (StringUtil.isEmpty(organization) || StringUtil.isEmpty(emailTheme)
                || StringUtil.isEmpty(emailContent) || StringUtil.isEmpty(receiver)) {
            return JsonUtils.getInstance().toJson(new ReturnModel(-1, "param error!"));
        }
        List<EmailInfo> emailInfos = emailService.queryEmailInfo(organization);
        //是否有邮件服务器
        if (emailInfos != null && !emailInfos.isEmpty()) {
            EmailInfo emailInfo = emailInfos.get(0);
            emailInfo.setEmailContent(emailContent);
            emailInfo.setEmailTheme(emailTheme);
            emailInfo.setEmailRemarks("");
            if (new MailUtil().send(emailInfo, receiver)) {
                return JsonUtils.getInstance().toJson(new ReturnModel(0, "send success!"));
            }
        }
        return JsonUtils.getInstance().toJson(new ReturnModel(-1, "send fail!"));
    }

}
